package eg;
import source.user;
import utils.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/*
 *@Student 张策
 */
public class Text1 {
    public static void main(String[] args) {
        List<user> findall = new Text1().findall();
        System.out.println(findall);
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        String name = scanner.nextLine();
        System.out.println("请输入密码");
        String password = scanner.nextLine();
        if(login(name, password)){
            System.out.println("登录成功");
        }else {
            System.out.println("登录失败");
        }
    }

public static boolean login(String name,String password){
    if(name==null||password==null){
        return false;
    }
    Connection conn=null;
    PreparedStatement pre=null;
    ResultSet resultSet=null;
    try {
        conn = JDBCUtils.getConnection();
        String sql="SELECT * FROM u WHERE NAME=? AND PASSWORD=?";
        pre = conn.prepareStatement(sql);
        pre.setString(1,name);
        pre.setString(2,password);
        resultSet = pre.executeQuery();
        return resultSet.next();
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        JDBCUtils.close(resultSet,pre,conn);
    }
    return false;
}
    public static List<user> findall(){
        List<user> list = new ArrayList<>();
        Statement statement=null;
        ResultSet re=null;
        Connection connection=null;
        try {
            //2.获取数据库连接对象
            connection = JDBCUtils.getConnection();
            //3.定义sql语言
            String mysql="select*from u";
            //获取执行sql的对象 statement
            statement = connection.createStatement();
            //执行sql
            re = statement.executeQuery(mysql);
            user acc=null;
            while (re.next()){
                int anInt = re.getInt("id");
                String string = re.getString("name");
                String anInt1 = re.getString("password");
                acc = new user();
                acc.setId(anInt);
                acc.setName(string);
                acc.setPassword(anInt1);
                list.add(acc);
            }
        }  catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(re,statement,connection);
        }
        return list;
    }
}

